#include "gifviewcontroller.h"
#include "gifview.h"
#include "gifwriter.h"
#include <QImage>
#include <QMovie>
#include <QFileInfo>
#include <QDir>
#include <QFileDialog>
#include <QApplication>
#include <QMessageBox>

CGIFViewController::CGIFViewController(QObject *parent)
    : QObject{parent}
{

}

void CGIFViewController::SetView(CGIFView *pView)
{
    m_pGIFView = pView;
}

void CGIFViewController::OpenGIF()
{
    static QString strLastUseDir = qApp->applicationDirPath();
    auto strFile = QFileDialog::getOpenFileName(m_pGIFView->window(), tr("Select gif"), strLastUseDir, "*.gif");
    QFileInfo fiSrc(strFile);
    if(!fiSrc.exists()) {
        return;
    }
    strLastUseDir = fiSrc.absolutePath();

    m_pGIFView->ShowGIF(strFile);
}

void CGIFViewController::ScaleGIF()
{
    auto strPath = m_pGIFView->GetShowGIFPath();
    auto size = m_pGIFView->GetScaleSize();
    QFileInfo fiSrc(strPath);
    if(!fiSrc.exists())
    {
        return;
    }
    QMovie movie;
    movie.setFileName(strPath);
    if(!movie.isValid())
    {
        return;
    }

    auto strName = fiSrc.baseName();
    auto dirDst = fiSrc.dir();
    auto strNewPath = dirDst.filePath(QString("%1_%2x%3.gif").arg(strName).arg(size.width()).arg(size.height()));

    GifWriter writer(strNewPath, size);
    bool bOk = true;
    for (int i = 0; i < movie.frameCount(); ++i) {
        movie.jumpToFrame(i);
        QImage frame = movie.currentImage();
        if (frame.isNull())
        {
            bOk = false;
            break;
        }
        QImage scaledFrame = frame
                .scaled(size.width(), size.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)
                .convertToFormat(QImage::Format_RGBA8888);

        if(!writer.AddFrame(scaledFrame, movie.nextFrameDelay()))
        {
            bOk = false;
            break;
        }
    }

    if(!bOk)
    {
        QFile::remove(strNewPath);
        QMessageBox::critical(m_pGIFView->window(), tr("tips"), tr(R"(Scale failed.)"));
    }
    else
    {
        QMessageBox::information(m_pGIFView->window(), tr("tips"), tr(R"(Scale success.
%1)").arg(strNewPath));
    }
}
